package org.asg.dis.service;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.validation.constraints.Pattern;
import org.asg.dis.model.Role;
import org.asg.dis.model.User;
import org.asg.dis.repository.RoleRepository;
import org.asg.dis.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private JwtService jwtService;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private UserRoleService userRoleService;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public String login(long userId, String password, String role) {
        User existingUser = userRepository.findByUserIdWithRoles(userId);
        System.out.println(existingUser);

        // 密码验证
        if (!passwordEncoder.matches(password, existingUser.getPassword())) {
            System.out.println("密码错误");
            throw new RuntimeException("密码错误");
        } else {
            System.out.println("密码正确");
        }

        List<Integer> roles = userRoleService.getUserRoles(userId);
        List<String> roleNames = roles.stream()
                .map(this::mapRoleIdToRoleName)
                .collect(Collectors.toList());
        // 检查role是否包含在用户的角色里
        if (!roleNames.contains(role)) {
            throw new RuntimeException("用户没有该角色权限");
        }

        System.out.println(roleNames);

        // 构建 Claims 对象
        Claims claims = Jwts.claims();
        claims.put("userId", existingUser.getUserId());
        claims.put("roles", role); // 使用转换后的角色名称列表

        System.out.println("Claims content before token generation: " + claims);

        try {
            // 调用 generateAndStoreToken
            return jwtService.generateAndStoreToken(userId, claims);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Token generation failed", e);
        }
    }

    private String mapRoleIdToRoleName(int roleId) {
        switch (roleId) {
            case 1: return "User";
            case 2: return "Courier";
            case 3: return "Stuff";
            case 4: return "Admin";
            default: return "Unknown"; // 默认值，处理未知的角色 ID
        }
    }

    public User signup(String name, String password, String phoneNumber) {
        if (name == null || name.isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (password == null || password.length() < 6) {
            throw new IllegalArgumentException("密码必须至少6位");
        }
        if (phoneNumber == null || !phoneNumber.matches("^\\d{10,15}$")) {
            throw new IllegalArgumentException("电话号码格式不正确");
        }

        if (getUserByPhone(phoneNumber) != null) {
            throw new RuntimeException("电话号码已被注册");
        }

        User user = new User();
        user.setUsername(name);
        user.setPassword(passwordEncoder.encode(password));
        user.setPhoneNumber(phoneNumber);

        return addUserWithRoles(user);
    }

    public void logout(String token) {
        jwtService.deleteToken(token);
    }
    public User createUser(User user) {

        return userRepository.save(user);
    }

    public Optional<User> getUserById(Long userId) {
        return userRepository.findById(userId); // 自动实现的查找
    }
    public List<Object[]> findUserRolesByUserId(Long userId){
        return userRepository.findUserRolesByUserId(userId);
    }
    public List<User> getAllUsers() {
        return userRepository.findAll(); // 自动实现的查找所有用户
    }

    public User updateUser(User user) {
        return userRepository.save(user); // 自动实现的更新
    }

    public void deleteUser(Long userId) {
        userRepository.deleteById(userId); // 自动实现的删除
    }

    public User getUserByPhone(@Pattern(regexp = "^\\S{5,16}$") String phone) {
        return userRepository.findByPhoneNumber(phone);
    }

    @Transactional
    public User addUserWithRoles(User u) {
        Role role1 = roleRepository.findById(1).orElseThrow(() -> new RuntimeException("Role not found"));

        Set<Role> roles = new HashSet<>();
        roles.add(role1);
        u.setRoles(roles);

        return userRepository.save(u);
    }

}
